package org.feichao.xdao.util;

import org.apache.commons.lang.StringUtils;

import java.util.Map;

/**
 * 表达式工具
 *
 * @author chao
 * @since 2015/5/27
 */
public class ExpressionUtil {

    /**
     * 获取表达式结果
     *
     * @param params
     * @param expressionStr
     * @return
     */
    public static Object get(Map<String, Object> params, String expressionStr){
        expressionStr = StringUtils.trimToEmpty(expressionStr);

        if(expressionStr.indexOf('.') > -1){
            String[] words = expressionStr.split("\\.");
            String objectName = words[0];
            String objectField = words[1];
            Object obj = params.get(objectName);
            if(obj == null){
                throw new RuntimeException("Cannot run expression:" + expressionStr);
            }
            return FieldAccessUtil.getter(obj, objectField);
        }else{
            return params.get(expressionStr);
        }
    }
}
